
#include "spi_port.h"

void spi_init(void)
{
    gpio_pad_select_gpio(RES_Pin);
    gpio_set_direction(RES_Pin, GPIO_MODE_OUTPUT);

    gpio_pad_select_gpio(DC_Pin);
    gpio_set_direction(DC_Pin, GPIO_MODE_OUTPUT);

    gpio_pad_select_gpio(CS_Pin);
    gpio_set_direction(CS_Pin, GPIO_MODE_OUTPUT);

    gpio_pad_select_gpio(SCK_Pin);
    gpio_set_direction(SCK_Pin, GPIO_MODE_OUTPUT);

    gpio_pad_select_gpio(SDI_Pin);
    gpio_set_direction(SDI_Pin, GPIO_MODE_OUTPUT);

    gpio_pad_select_gpio(BUSY_Pin);
    gpio_set_direction(BUSY_Pin, GPIO_MODE_INPUT);


    gpio_pad_select_gpio(E_3V3_Pin);
    gpio_set_direction(E_3V3_Pin, GPIO_MODE_OUTPUT);
    EPD_POWER_ON;
}

void epd_delay_us(uint32_t us) 
{ 
    usleep(us); 
}

void epd_delay_ms(uint32_t ms) 
{ 
    vTaskDelay(ms / portTICK_RATE_MS); 
}

void epd_delay_s(uint32_t s)
{
    for (int i = s; i > 0; i--) {
        vTaskDelay(1000 / portTICK_RATE_MS);
    }
}

void spi_delay(unsigned char xrate)
{
    unsigned char i;
    while (xrate) {
        for (i = 0; i < 2; i++)
            ;
        xrate--;
    }
}

void spi_write(unsigned char value)
{
    unsigned char i;
    spi_delay(1);
    for (i = 0; i < 8; i++) {
        EPD_W21_CLK_0;
        spi_delay(1);
        if (value & 0x80)
            EPD_W21_MOSI_1;
        else
            EPD_W21_MOSI_0;
        value = (value << 1);
        spi_delay(1);
        epd_delay_us(1);
        EPD_W21_CLK_1;
        spi_delay(1);
    }
}

void epd_power_off(void) 
{ 
    EPD_POWER_OFF;
}

void epd_power_on(void) 
{ 
    EPD_POWER_ON;
}

